/* eslint-disable no-use-before-define */
import useInitialState from '@/hooks/useInitialState'
import { logout } from '@/store/actions/login'
import { getUserProfile, updateUserPhoto, updateUserProfile } from '@/store/actions/profile'
import { formatDay } from '@/utils'
import { Button, List, DatePicker, NavBar, Popup, Toast, Dialog } from 'antd-mobile'
import classNames from 'classnames'
import React, { useRef, useState } from 'react'
import { useDispatch } from 'react-redux'
import { useHistory } from 'react-router-dom'
import EditInput from './EditInput'
import EditList from './EditList'

import styles from './index.module.scss'

const Item = List.Item
type ShowInputType = { visible: boolean, type: '' | 'name' | 'intro'}
type ShowListType = { visible: boolean, type: '' | 'gender' | 'photo'}

const ProfileEdit = () => {
  const history = useHistory()
  const inputFileRef = useRef<HTMLInputElement>(null)
  const dispatch = useDispatch()
  // { visible: false, type: '' }
  // visible:控制是否显示弹框, type：决定当前要编辑的是：昵称还是简介
  const [showInput, setShowInput] = useState<ShowInputType>({ visible: false, type: '' })
  // 定义一个用来关闭弹框的函数
  const hideInput = () => {
    setShowInput({ visible: false, type: '' })
  }

  // visible:控制是否显示弹框, type：决定当前要编辑的是：性别还是头像
  const [showList, setShowList] = useState<ShowListType>({ visible: false, type: '' })
  const hideList = () => {
    setShowList({ visible: false, type: '' })
  }

  const [showBirthday, setShowBirthday] = useState(false)
  const onUpdateBirthday = async (e: Date) => {
    console.log(e)
    // 用户的生日 e
    // 调用修改生日
    await onUpdate('birthday', formatDay(e))

    setShowBirthday(false)
  }
  const { userProfile } = useInitialState(getUserProfile, 'profile')

  // 定义一个用来接收子组件修改之后的值
  const onUpdate = async (type:string, value: string) => {
    // 特殊处理 photo的情况
    if (type === 'photo') {
      // 要打开文件域组件 --> [ input - type:file ] .进而让用户选择图片
      // 模拟 手动click [ input - type:file ]
      // alert('让用户选择图片')
      inputFileRef.current?.click()
      return
    }

    // 1. 提交数据
    await dispatch(updateUserProfile(type, value))
    Toast.show({
      icon: 'success',
      content: '修改成功'
    })
    // 2. 关闭弹框
    hideInput()
    hideList()
  }

  // 用户在input:type file 中选择了图片
  const onChangeFile = async (e: React.ChangeEvent<HTMLInputElement>) => {
    const file = e.target.files![0]
    if (!file) {
      return
    }
    // 这里要上传是文件，必须使用FormData
    const formData = new FormData()
    formData.append('photo', file)

    await dispatch(updateUserPhoto(formData))

    Toast.show({
      icon: 'success',
      content: '修改成功'
    })
    // 2. 关闭弹框
    hideList()
  }

  const onLogout = () => {
    // 用户确认退出
    const handler = Dialog.show({
      title: '温馨提示',
      content: '亲，你确定退出吗？',
      closeOnAction: true,
      actions: [
        [
          {
            key: 'cancel',
            text: '取消',
            onClick: () => {
              handler.close()
            }
          },
          {
            key: 'confirm',
            text: '退出',
            onClick: () => {
              // 做具体的退出的动作
              // 1. dispatch
              dispatch(logout())
              // 2. action ( 1. 删除登录信息[redux, localstorage]； 2. 根据情况调用退出接口  )
              // 3. 页面跳转 --> login
              history.replace('/login', { from: history.location.pathname })
              Toast.show({ content: '退出成功' })
            },
            style: {
              color: 'var(--adm-color-weak)'
            }
          }
        ]
      ]
    })
  }
  return (
    <div className={styles.root}>
      <div className="content">
        {/* 标题 */}
        <NavBar
          onBack={() => history.go(-1)}
          style={{
            '--border-bottom': '1px solid #F0F0F0'
          }}
        >
          个人信息
        </NavBar>

        <div className="wrapper">
          {/* 列表 */}
          <List className="profile-list">
            {/* 列表项 */}
            <Item
              extra={
                <span className="avatar-wrapper">
                  <img
                    width={24}
                    height={24}
                    src={userProfile.photo}
                    alt=""
                  />
                </span>
              }
              onClick={() => setShowList({ visible: true, type: 'photo' })}
              arrow
            >
              头像
            </Item>
            <input type='file' ref={inputFileRef} hidden onChange={ onChangeFile }/>
            <Item arrow extra={userProfile.name} onClick={() => setShowInput({ visible: true, type: 'name' })}>
              昵称
            </Item>
            <Item
              arrow
              extra={
                <span className={classNames('intro', 'normal')}>
                  {userProfile.intro}
                </span>
              }
              onClick={() => setShowInput({ visible: true, type: 'intro' })}
            >
              简介
            </Item>
          </List>

          <List className="profile-list">
            <Item arrow extra={userProfile.gender ? '女' : '男'} onClick={() => setShowList({ visible: true, type: 'gender' })}>
              性别
            </Item>
            <Item arrow extra={userProfile.birthday} onClick={() => setShowBirthday(true)}>
              生日
            </Item>
          </List>

          <DatePicker
            visible={showBirthday}
            value={new Date(userProfile.birthday)}
            onCancel={() => setShowBirthday(false)}
            onConfirm={ onUpdateBirthday}
            title="选择生日"
            min={new Date('1980-01-01')}
            max={new Date()}
          />
        </div>

        <div className="logout">
          <Button className="btn" onClick={onLogout}>退出登录</Button>
        </div>
      </div>
      {/* 编辑昵称和简介 */}
      <Popup visible={showInput.visible} position="right" destroyOnClose>
        <EditInput hideInput={hideInput} type={showInput.type} onUpdate={onUpdate}/>
      </Popup>

      {/* 编辑性别和头像 */}
      <Popup onMaskClick={hideList} visible={showList.visible} position="bottom" destroyOnClose>
        <EditList hideList={hideList} type={showList.type} onUpdate={onUpdate}/>
      </Popup>
    </div>
  )
}

export default ProfileEdit
